package com.ball.dev.service.impl;

import com.ball.common.dtos.PageQuery;
import com.ball.common.dtos.ResponseResult;
import com.ball.common.enums.AppHttpCodeEnum;
import com.ball.common.utils.*;
import com.ball.dev.entity.dto.PushDto;
import com.ball.dev.entity.po.*;
import com.ball.dev.entity.vo.PostVo;
import com.ball.dev.mapper.PostCollectMapper;
import com.ball.dev.mapper.PostLikesMapper;
import com.ball.dev.mapper.PostMapper;
import com.ball.dev.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 帖子 服务实现类
 * </p>
 *
 * @author lou
 * @since 2024-03-04
 */
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    private final IPersonalService personalService;
    private final IAppUserService userService;
    private final PostLikesMapper postLikesMapper;
    private final PostCollectMapper postCollectMapper;
    private final ICareService careService;
    private final IPostCommentService commentService;
    @Override
    @Transactional
    //添加中文注释后
public ResponseResult addPost(Post postDto) {
        //判断postDto是否为空
        if (postDto == null){
            //如果为空，返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请先添加数据");
        }
        //内容和photos 必须添加一个
        if (StringUtils.isBlank(postDto.getContext()) && StringUtils.isBlank(postDto.getPhotos())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"必须填写一个");
        }

        //判断是视频还是照片
        if (StringUtils.isNotBlank(postDto.getPhotos())){
            int type = FileExtensionChecker.checkFileType(postDto.getPhotos());
            postDto.setType(type);
        }


        //设置创建时间和更新时间
        postDto.setCreateTime(LocalDateTime.now());
        postDto.setUpdateTime(LocalDateTime.now());



        //保存postDto
        return save(postDto) ? ResponseResult.okResult("添加成功") : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"业务繁忙，请稍后重试");
    }

    @Override
   public ResponseResult postList(PageQuery query) {
        //将PageQuery转换为Page
        Page<PostVo> queryMpPage = query.toMpPage();
        //调用baseMapper的getPostList方法，获取分页数据
        Page<PostVo> page = baseMapper.getPostList(queryMpPage);

        //获取分页数据
        List<PostVo> records = page.getRecords();
        //判断是否有数据
        if (CollUtils.isEmpty(records)){
            //没有数据，返回提示信息
            return  ResponseResult.okResult("还没有相关数据，请添加数据");
        }
        //有数据，返回分页数据
        return ResponseResult.okResult(page);
    }

    @Override
    @Transactional
    public ResponseResult addPushPost(PushDto pushDto) {
       //校验参数
  if (pushDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不合法");
        }

        //校验用户id
        if (pushDto.getUserId()== null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户id不能为空");
        }
        //校验用户
        AppUser user = userService.lambdaQuery().eq(AppUser::getId, pushDto.getUserId())
                .eq(AppUser::getStatus, 0)
                .eq(AppUser::getManageStatus, 1).one();

        if (user == null){//需要为管理员权限
           return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }

        //校验帖子id
        if (pushDto.getPostId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"帖子id不能为空");
        }

        Post post = new Post();
        post.setId(pushDto.getPostId());
        post.setPush(pushDto.getPush());

        return  updateById(post)?ResponseResult.okResult("添加成功"):ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @Override

    public ResponseResult getPushList(PageQuery query) {

      Page page=  baseMapper.getPushPostList(query.toMpPage());

        List records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"还没有推荐帖子，联系管理员进行添加");
        }

        return ResponseResult.okResult(page);

    }

    @Override
    @Transactional
   // 修改帖子
    public ResponseResult updatePost(Post postDto) {
        // 判断帖子是否为空
        if (postDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"帖子不能为空");
        }

        // 判断帖子id是否为空
        if (postDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"帖子id不能为空");
        }

        // 调用updateById方法修改帖子
        return updateById(postDto)?
                ResponseResult.okResult("修改成功"):ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);

    }

    @Override
   // 根据id删除帖子
    public ResponseResult deletePost(String id,Integer status) {
        // 判断id是否为空
        if (id == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"帖子id不能为空");
        }
        // 创建一个帖子对象
        Post post = new Post();
        // 设置帖子的id
        post.setId(id.toString());
        // 设置帖子的状态为已删除
        post.setStatus(status);
        // 设置帖子的更新时间
        post.setUpdateTime(LocalDateTime.now());
        // 返回更新结果
        return updateById(post)?
                ResponseResult.okResult("操作成功"):ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @Override
    public ResponseResult getPostById(String id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"帖子id不能为空");
        }
        Post post = getById(id);
        if (post == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "帖子不存在");
        }
        Personal personal = personalService.lambdaQuery().eq(Personal::getUserId, post.getUserId()).one();



        PostVo postVo = BeanUtils.copyBean(post, PostVo.class);
        postVo.setUserName(personal.getUserName());
        postVo.setPhoto(personal.getPhoto());

        //获取用户id
        String userId = UserContext.getUser();

        //判断用户是否点赞
        PostLikes likes = postLikesMapper.selectOne(Wrappers.<PostLikes>lambdaQuery().eq(PostLikes::getPostId, post.getId())
                .eq(PostLikes::getUserId, userId));

        if (likes != null){
            postVo.setIsLike(likes.getStatus());
        }else {
            postVo.setIsLike(1);
        }

        //判断用户是否收藏
        PostCollect collect = postCollectMapper.selectOne(Wrappers.<PostCollect>lambdaQuery().eq(PostCollect::getPostId, post.getId())
                .eq(PostCollect::getUserId, userId));
        if (collect != null){
            postVo.setIsCollect(collect.getStatus());
        }else {
            postVo.setIsCollect(1);
        }
        //判断用户是否关注
        Care care = careService.lambdaQuery().eq(Care::getUserId, userId).eq(Care::getCareId, post.getUserId()).one();
        if (care != null){
            postVo.setIsFollow(care.getStatus());
        }else {
            postVo.setIsFollow(1);
        }

        //获取评论
        List<PostComment> comments = commentService.lambdaQuery()
                .eq(PostComment::getPostId, post.getId())
                .eq(PostComment::getStatus, 0)
                .orderByDesc(PostComment::getCreateTime)
                .list();
        postVo.setComments(comments);


        return ResponseResult.okResult(postVo);
    }

    @Override
    public ResponseResult careList() {
        //获取当前用户id
        String userId = UserContext.getUser();
        //查询当前用户id下的待处理事项
        List<Care> cares = careService.lambdaQuery().eq(Care::getUserId, userId).eq(Care::getStatus, 0).list();


        ArrayList<String> careUserIds = new ArrayList<>();

        //如果查询结果不为空，则将查询结果中的careId添加到careUserIds中
        if (CollUtils.isNotEmpty(cares)){
            cares.forEach(care -> {
                careUserIds.add(care.getCareId());
            });
        }
        ArrayList<PostVo> postVos = new ArrayList<>();
        //如果careUserIds不为空，则遍历careUserIds
        if (CollUtils.isNotEmpty(careUserIds)){



            for (String careUserId : careUserIds) {
                //查询careUserId下的待处理事项
                lambdaQuery().eq(Post::getUserId, careUserId).eq(Post::getStatus, 0).list()
                        .forEach(post -> {
                    //将查询结果中的post对象转换为PostVo对象
                    PostVo postVo = BeanUtils.copyBean(post, PostVo.class);
                    //根据careUserId查询Personal对象
                    Personal personal = personalService.lambdaQuery().eq(Personal::getUserId, careUserId).one();
                    //将查询结果中的photo赋值给PostVo对象
                    postVo.setPhoto(personal.getPhoto());
                    //将查询结果中的userName赋值给PostVo对象
                    postVo.setUserName(personal.getUserName());
                    //将PostVo对象添加到postVos中
                    postVos.add(postVo);
                });
            }
        }

        //返回查询结果
        return ResponseResult.okResult(postVos);

    }


    @Override
   public ResponseResult getMyLikePost() {
        //获取当前用户id
        String userId = UserContext.getUser();

        //查询当前用户id，状态为0的点赞信息
        List<PostLikes> postLikes = postLikesMapper.selectList(new LambdaQueryWrapper<PostLikes>()
                .eq(PostLikes::getUserId, userId).eq(PostLikes::getStatus, 0));

        ArrayList<PostVo> postVos = new ArrayList<>();
        if (CollUtils.isNotEmpty(postLikes)) {

            //遍历点赞信息，根据点赞信息获取文章信息
            postLikes.forEach(postLike -> {
                        Post post = getById(postLike.getPostId());
                        PostVo postVo = BeanUtils.copyBean(post, PostVo.class);
                        //获取当前文章作者信息
                        Personal personal = personalService.lambdaQuery().eq(Personal::getUserId, post.getUserId()).one();
                        postVo.setPhoto(personal.getPhoto());
                        postVo.setUserName(personal.getUserName());
                        postVos.add(postVo);
                    }
            );
        }

        return ResponseResult.okResult(postVos);
    }

    @Override
    public ResponseResult getMyCollectPost() {
        //获取当前用户id
        String userId = UserContext.getUser();

        //查询当前用户id，状态为0的点赞信息
        List<PostCollect> postcollects = postCollectMapper.selectList(new LambdaQueryWrapper<PostCollect>()
                .eq(PostCollect::getUserId, userId).eq(PostCollect::getStatus, 0));

        ArrayList<PostVo> postVos = new ArrayList<>();
        if (CollUtils.isNotEmpty(postcollects)) {

            //遍历点赞信息，根据点赞信息获取文章信息
            postcollects.forEach(postCollect -> {
                        Post post = getById(postCollect.getPostId());
                        PostVo postVo = BeanUtils.copyBean(post, PostVo.class);
                        //获取当前文章作者信息
                        Personal personal = personalService.lambdaQuery().eq(Personal::getUserId, post.getUserId()).one();
                        postVo.setPhoto(personal.getPhoto());
                        postVo.setUserName(personal.getUserName());
                        postVos.add(postVo);
                    }
            );
        }

        return ResponseResult.okResult(postVos);
    }
}
